package com.student.score.system;

import com.student.score.entity.Course;
import com.student.score.entity.Student;
import com.student.score.entity.Score;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class ScoreSystem {
    // 保存数据到文件
    public static void saveToFile(List<Student> students, List<Course> courses, String filename) {
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(filename));

            // 先写课程信息
            writer.write("===课程信息===");
            writer.newLine();
            for (Course course : courses) {
                writer.write(String.format("课程:%s,%s,%d", 
                    course.getId(), course.getName(), course.getCredit()));
                writer.newLine();
            }

            // 再写学生及成绩信息
            writer.write("===学生信息===");
            writer.newLine();
            for (Student student : students) {
                writer.write(String.format("学生:%s,%s,%s", 
                    student.getId(), student.getName(), student.getClassName()));
                writer.newLine();
                for (Score score : student.getScores()) {
                    writer.write(String.format("成绩:%s,%d", 
                        score.getCourse().getId(), score.getScore()));
                    writer.newLine();
                }
            }
            System.out.println("数据已保存到文件：" + filename);
        } catch (IOException e) {
            System.err.println("保存文件时发生错误：" + e.getMessage());
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    System.err.println("关闭文件流时发生错误：" + e.getMessage());
                }
            }
        }
    }

    // 从文件加载数据（补充完整加载逻辑）
    public static void loadFromFile(List<Student> students, List<Course> courses, String filename) {
        // 这里省略了从文件加载数据的具体实现，可根据实际需求补充
        // 大致思路是使用BufferedReader读取文件内容，解析后填充students和courses集合
        System.out.println("从文件加载数据的方法待完善");
    }
}